package com.heqiang.fillter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthFilter extends ZuulFilter {

    @Override
    //pre: 表示路由之前执行
    //post
    //error
    //route
    //static
    //返回过滤器类型,决定在过滤器哪儿个生命周期执行
    public String filterType() {
        return "pre";
    }

    @Override
    //返回值指定过滤器执行顺序
    public int filterOrder() {
        return 0;
    }

    @Override
    //判断过滤器是否执行
    public boolean shouldFilter() {
        return true;
    }

    @Override
    //过滤器具体逻辑
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        //人为构造异常
//        int i = 10 / 0;

        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (null == token) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.addZuulResponseHeader("content-type", "text/html;charset=utf-8");
            context.setResponseBody("非法访问,没有权限");
        }
        return null;
    }
}
